package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements  OrderSettingService {
    @Autowired
    OrderSettingDao orderSettingDao;

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        Integer count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (null != count && count > 0) {
            orderSettingDao.editNumberByOrderDate(orderSetting);
        } else {
            orderSettingDao.add(orderSetting);
        }
    }

    @Override
    public void setNumberByDateBatch(List<OrderSetting> orderSettings) {

        if (orderSettings != null && orderSettings.size() > 0) {
            for (OrderSetting orderSetting : orderSettings) {

                editNumberByDate(orderSetting);
            }
        }
        //使用多线程导入

        //1、把数据（orderSettings）拆分
//        List<List<OrderSetting>> partition = Lists.partition(orderSettings, 20);
//
//        //2、搞一个线程池
//        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

//        for (List<OrderSetting> settings : partition) {
//            executorService.submit(new Runnable() {
//                @Override
//                public void run() {
//                    for (OrderSetting orderSetting : settings) {
//                        editNumberByDate(orderSetting);
//                    }
//                }
//            });
//        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        String start = date + "-01";
        String end = date + "-31";
        Map mapParam = new HashMap();
        mapParam.put("start", start);
        mapParam.put("end", end);
        List<OrderSetting> orderSettings = orderSettingDao.getOrderSettingByMonth(mapParam);
        //要把ordersetting转成 {"date":22,"mouth":10,"number":300,"reservations":300,}
        List<Map> result = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            Map map = new HashMap();
            map.put("number", orderSetting.getNumber());
            map.put("reservations", orderSetting.getReservations());
            Date orderDate = orderSetting.getOrderDate();
            map.put("date", orderDate.getDate());
            map.put("mouth", orderDate.getMonth());
            result.add(map);
        }
        return result;
    }
}